#include "mainwindow.h"
#include "ui_mainwindow.h"

#include<QtCore>
/////////////////////////
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    captureWebcam.open(0);

    if(captureWebcam.isOpened()== false)
    {
        ui->txtXY->setText("error, try again");
        return;
    }

    tmrTimer = new QTimer(this);

    connect(tmrTimer, SIGNAL(timeout()), this, SLOT(processFrameAndUpdateGUI()));
    tmrTimer->start(20);
}

////////////////////////////
MainWindow::~MainWindow()
{
    delete ui;
}
////////////////////////////
void MainWindow::processFrameAndUpdateGUI()
{
    captureWebcam.read(matOrignal);

    if(matOrignal.empty() == true)
    {
        return;
    }

    cv::inRange(matOrignal, cv::Scalar(0, 0, 175), cv::Scalar(100, 100, 256), matProcessed);
    cv::GaussianBlur(matProcessed, matProcessed, cv::Size(9,9), 1, 5);
    cv::HoughCircles(matProcessed, vecCircles, CV_HOUGH_GRADIENT, 2, matProcessed.rows / 4, 100, 50, 10, 400);

    for(irtCircles= vecCircles.begin(); irtCircles!= vecCircles.end(); irtCircles++)
    {
        ui->txtXY->setText("x= "+ QString::number((*irtCircles)[0]) +" Y= "+ QString::number((*irtCircles)[1]));
        cv::circle(matOrignal, cv::Point((int)(*irtCircles)[0], (int)(*irtCircles)[1]), 3, cv::Scalar(0, 255, 0), CV_FILLED);
        cv::circle(matOrignal, cv::Point((int)(*irtCircles)[0], (int)(*irtCircles)[1]), (int)(*irtCircles)[2], cv::Scalar(0, 0, 255), 3);

    }

    cv::cvtColor(matOrignal, matOrignal, CV_RGB2BGR);

    QImage qimgOrignal((uchar*)matOrignal.data, matOrignal.cols, matOrignal.rows, matOrignal.step, QImage::Format_RGB888);
    QImage qimgProcessed((uchar*)matProcessed.data, matProcessed.cols, matProcessed.rows, matProcessed.step, QImage::Format_Indexed8);

    ui->lbOrignal->setPixmap(QPixmap::fromImage(qimgOrignal));
    ui->lbProcessed->setPixmap(QPixmap::fromImage(qimgProcessed));

}
//////////////////////////////////////
void MainWindow::on_btnPause_clicked()
{
    if(tmrTimer->isActive() == true)
    {
        tmrTimer->stop();
        ui->btnPause->setText("resume");
    }
    else
    {
        tmrTimer->start(20);
        ui->btnPause->setText("pause");
    }
}
